package com.fleafinder;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.Session;

public class MainActivity extends FragmentActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// It's enough to remove the line
		// requestWindowFeature(Window.FEATURE_NO_TITLE);
		// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
		// WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.activity_main);
		DataCenter dataCenter = DataCenter.getInstance();
		dataCenter.setContext(this);
		dataCenter.startLoadingData();
		dataCenter.setCurrentSelectedTab(CommonConstants.TAB_HOME);

		while (dataCenter.isLoadingMarketTypeList()) {
			try {
				Thread.sleep(CommonConstants.DEFAULT_SLEEP_TIME);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		while (dataCenter.isLoadingBusinessMarket()) {
			try {
				Thread.sleep(CommonConstants.DEFAULT_SLEEP_TIME);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		Display display = getWindowManager().getDefaultDisplay();
		dataCenter.setScreenSize(display.getWidth(), display.getHeight());
		dataCenter.setRootFragmentOfTab(true);

		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction transaction = fm.beginTransaction();
		transaction.setTransition(FragmentTransaction.TRANSIT_ENTER_MASK);
		transaction.add(R.id.fragment_placeholder, DataCenter.getInstance()
				.getHomeScreenFragment(), CommonConstants.HOME_FRAGMENT);
		transaction.addToBackStack(CommonConstants.HOME_FRAGMENT);
		transaction.commit();
		Log.i("FR", "APP START LOG");
		LogBackStack();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void onTabClick(View v) {
		Log.i("FR", "TAB CLICK LOG");
		LogBackStack();
		DataCenter dc = DataCenter.getInstance();
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction fragmentTransaction = fm.beginTransaction();

		int count = fm.getBackStackEntryCount();
		String currentFragName = fm.getBackStackEntryAt(count - 1).getName();

		fragmentTransaction
				.setTransition(FragmentTransaction.TRANSIT_ENTER_MASK);
		String tag = null;

		if (v == findViewById(R.id.tabs_home)) {
			while (count > 1) {
				fm.popBackStackImmediate();
				count--;
			}

			removeSelectedTab();
			SelectedTab(R.id.tabs_home, R.id.tab_home_img, R.id.tab_home_text,
					R.drawable.home_selected);
			dc.setCurrentSelectedTab(CommonConstants.TAB_HOME);
			return;

		} else if (v == findViewById(R.id.tabs_topmarket)) {

			if (currentFragName == CommonConstants.TOP_FRAGMENT
					&& dc.isRootFragmentOfTab() == true)
				return;
			dc.setSaveCurrentMarketListMode(dc.getCurrentMarketListMode());

			removeSelectedTab();
			SelectedTab(R.id.tabs_topmarket, R.id.tabs_topmarket_img,
					R.id.tabs_topmarket_text, R.drawable.cup_selected);
			dc.setCurrentSelectedTab(CommonConstants.TAB_TOPMARKET);
			dc.setCurrentMarketListMode(CommonConstants.TOP_MARKEDER);
			tag = CommonConstants.TOP_FRAGMENT;

			fragmentTransaction.replace(R.id.fragment_placeholder,
					dc.getMarketListFragmentForTopMarkeder(), tag);

		} else if (v == findViewById(R.id.tabs_map)) {

			if (currentFragName == CommonConstants.MAP_FRAGMENT
					&& dc.isRootFragmentOfTab() == true)
				return;

			removeSelectedTab();
			SelectedTab(R.id.tabs_map, R.id.tabs_map_img, R.id.tabs_map_text,
					R.drawable.globe_selected);
			dc.setCurrentSelectedTab(CommonConstants.TAB_MAP);
			tag = CommonConstants.MAP_FRAGMENT;

			if (dc.getMapScreenFragment() != null) {
				dc.getMapScreenFragment().reset();
				dc.getMapScreenFragment().updateUserCurrentLocation();
				dc.getMapScreenFragment().updateMarketMarkersToMap(true);
			}

			fragmentTransaction.replace(R.id.fragment_placeholder,
					dc.getMapScreenFragmentContainer(), tag);

		} else if (v == findViewById(R.id.tabs_open)) {
			if (currentFragName == CommonConstants.OPEN_FRAGMENT
					&& dc.isRootFragmentOfTab() == true)
				return;

			removeSelectedTab();
			SelectedTab(R.id.tabs_open, R.id.tabs_open_img,
					R.id.tabs_open_text, R.drawable.shop_selected);
			dc.setCurrentSelectedTab(CommonConstants.TAB_OPENMARKET);
			tag = CommonConstants.OPEN_FRAGMENT;
			fragmentTransaction.replace(R.id.fragment_placeholder,
					dc.getOpenMarketFragment(), tag);

		}
		dc.setRootFragmentOfTab(true);
		fragmentTransaction.addToBackStack(tag);
		fragmentTransaction.commit();

	}

	private void removeSelectedTab() {
		int currentSelectedTab = DataCenter.getInstance()
				.getCurrentSelectedTab();

		if (currentSelectedTab == CommonConstants.TAB_HOME) {
			removeSelectedTab(R.id.tabs_home, R.id.tab_home_img,
					R.id.tab_home_text, R.drawable.home);
		} else if (currentSelectedTab == CommonConstants.TAB_MAP) {
			removeSelectedTab(R.id.tabs_map, R.id.tabs_map_img,
					R.id.tabs_map_text, R.drawable.globe);
		} else if (currentSelectedTab == CommonConstants.TAB_OPENMARKET) {
			removeSelectedTab(R.id.tabs_open, R.id.tabs_open_img,
					R.id.tabs_open_text, R.drawable.shop);
		} else if (currentSelectedTab == CommonConstants.TAB_TOPMARKET) {
			removeSelectedTab(R.id.tabs_topmarket, R.id.tabs_topmarket_img,
					R.id.tabs_topmarket_text, R.drawable.cup);
		}
	}

	private void removeSelectedTab(int tabId, int imageId, int textId,
			int imageBgrId) {
		LinearLayout tab = (LinearLayout) findViewById(tabId);
		tab.setBackgroundResource(R.drawable.tab_bgr);

		TextView text = (TextView) findViewById(textId);
		text.setTextColor(Color.parseColor("#898995"));

		ImageView img = (ImageView) findViewById(imageId);
		img.setImageResource(imageBgrId);
	}

	private void SelectedTab(int tabId, int imageId, int textId, int imageBgrId) {
		LinearLayout tab = (LinearLayout) findViewById(tabId);
		tab.setBackgroundResource(R.drawable.selectedtab_bgr);

		TextView text = (TextView) findViewById(textId);
		text.setTextColor(Color.parseColor("#FFFFFF"));

		ImageView img = (ImageView) findViewById(imageId);
		img.setImageResource(imageBgrId);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		DataCenter dc = DataCenter.getInstance();

		FragmentManager fm = getSupportFragmentManager();
		int count = fm.getBackStackEntryCount();
		Log.i("FR", "COUNT ON BACK CLICKED : " + count);
		if (count <= 1) {
			finish();
			System.exit(0);
		}
		// removeSelectedTab();

		String currentTab = fm.getBackStackEntryAt(count - 1).getName();
		if (currentTab != CommonConstants.HOME_FRAGMENT) {
			if (dc.isRootFragmentOfTab()) {
				Log.i("FR", "COUNT ON BACK CLICKED : First");
				while (count > 2) {
					fm.popBackStackImmediate();
					count--;
				}
				removeSelectedTab();
				dc.setCurrentMarketListMode(dc.getSaveCurrentMarketListMode());
				Log.i("FR",
						"COUNT ON BACK CLICKED : MODE"
								+ dc.getCurrentMarketListMode());
				dc.setCurrentSelectedTab(CommonConstants.TAB_HOME);
				SelectedTab(R.id.tabs_home, R.id.tab_home_img,
						R.id.tab_home_text, R.drawable.home_selected);
			} else {
				while (count > 2) {
					String prevTabs = fm.getBackStackEntryAt(count - 3)
							.getName();
					if (prevTabs == currentTab) {
						fm.popBackStackImmediate();
						count--;
					} else {
						dc.setRootFragmentOfTab(true);
						break;
					}
				}
			}
		}

		// if (currentTab != CommonConstants.HOME_FRAGMENT) {
		// String prevTab = fm.getBackStackEntryAt(count - 2).getName();
		// Log.i("FR", "COUNT ON BACK CLICKED : First" + prevTab + currentTab);
		// if (prevTab != currentTab) {
		// Log.i("FR", "COUNT ON BACK CLICKED : First");
		// while (count > 2) {
		// fm.popBackStackImmediate();
		// count--;
		// }
		// removeSelectedTab();
		// dc.setCurrentMarketListMode(dc.getSaveCurrentMarketListMode());
		// Log.i("FR",
		// "COUNT ON BACK CLICKED : MODE"
		// + dc.getCurrentMarketListMode());
		// dc.setCurrentSelectedTab(CommonConstants.TAB_HOME);
		// SelectedTab(R.id.tabs_home, R.id.tab_home_img,
		// R.id.tab_home_text, R.drawable.home_selected);
		// } else {
		// Log.i("FR", "COUNT ON BACK CLICKED : Second");
		// while (count > 2) {
		// String prevTabs = fm.getBackStackEntryAt(count - 3)
		// .getName();
		// if (prevTabs != CommonConstants.HOME_FRAGMENT) {
		// fm.popBackStackImmediate();
		// count--;
		// } else
		// break;
		// }
		// }
		// }

		Log.i("FR", "COUNT ON BACK CLICKED : SUPPERs");
		super.onBackPressed();

		LogBackStack();
	}

	public void LogBackStack() {

		FragmentManager m = getSupportFragmentManager();
		for (int i = 0; i < m.getBackStackEntryCount(); i++) {
			Log.i("FR", "Frangemet at " + i + ":"
					+ m.getBackStackEntryAt(i).getName() + " || id "
					+ m.getBackStackEntryAt(i).getId());
		}
		Log.i("FR", "END LOG");
	}

	public Boolean GetBacktoState(String fragmentName) {
		Boolean isSucceed = false;
		FragmentManager fm = getSupportFragmentManager();
		int count = fm.getBackStackEntryCount();
		while (count > 0) {
			String name = fm.getBackStackEntryAt(count - 1).getName();
			int id = fm.getBackStackEntryAt(count - 1).getId();
			if (name != fragmentName) {
				fm.popBackStackImmediate(id,
						FragmentManager.POP_BACK_STACK_INCLUSIVE);
				Log.i("FR", "POP FRAG : " + name);
			} else {
				isSucceed = true;
				Log.i("FR", "# FRAG after pop: " + fm.getBackStackEntryCount());
				//
				return isSucceed;
			}
			count--;
		}
		return isSucceed;
	}

	public Boolean BacktoParentFragment(String fragmentName) {

		/*
		 * 1. Get current tab
		 * 
		 * 2. If is Home or Prev item in stack is home, pop to last one
		 */

		Boolean isSucceed = false;
		FragmentManager fm = getSupportFragmentManager();
		int count = fm.getBackStackEntryCount();
		while (count > 0) {
			String name = fm.getBackStackEntryAt(count - 1).getName();
			int id = fm.getBackStackEntryAt(count - 1).getId();
			if (name != fragmentName) {
				fm.popBackStackImmediate(id,
						FragmentManager.POP_BACK_STACK_INCLUSIVE);
				Log.i("FR", "POP FRAG : " + name);
			} else {
				isSucceed = true;
				Log.i("FR", "# FRAG after pop: " + fm.getBackStackEntryCount());
				//
				return isSucceed;
			}
			count--;
		}
		return isSucceed;
	}
	// public String GetActiveFragment() {
	// if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
	// return null;
	// }
	// //String tag = getSupportFragmentManager().getBackStackEntryAt(arg0)
	// }
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode,
				resultCode, data);
	}
}
